# encoding: utf-8
import os

from datetime import datetime
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import models

class BaseRequestHandler(webapp.RequestHandler):
	"""Base classs"""
	def generate(self, template_name, template_values={}):
		values = {
		}
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values))

class default(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		if bookmark_id:
			time_date_b = models.Article.get_by_id(int(bookmark_id)).time_date
			articles = models.Article.all().order('-time_date').filter('time_date <=',time_date_b).fetch(limit=9)
			pre_articles = models.Article.all().order('time_date').filter('time_date >',time_date_b).fetch(limit=8)
		else:
			articles = models.Article.all().order('-time_date').fetch(limit=9)
			pre_articles = None
		values = {
			'articles': articles[:8],
		}
		if len(articles) == 9:
			value_next = {
				'next_page': articles[8]
			}
			values.update(value_next)
		if (pre_articles) and (len(pre_articles)>0):
			value_pre = {
				'pre_page': pre_articles[-1]
			}
			values.update(value_pre)
		self.generate('root_base.html',values)
	def post(self):
		key_d = self.request.get('key_hidden')
		content_form = self.request.get('content_form')
		if key_d:
			db.delete(db.Key(key_d))
			self.redirect(self.request.uri)
		elif content_form:
			new_article = models.Article(content=content_form)
			new_article.put()
			self.redirect('/root.html')

def main():
	application = webapp.WSGIApplication([
		('/root.html$', default),
	],debug=True)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
